import numpy as np
from Core.init_city_index_distance import *

'''
个体类
'''


class Individual:
    def __init__(self, genes=None, genes_len=0, dist_mat=None):
        if genes is None:
            # 如果是第一次, 需要随机生成"gene"序列, 此处每个个体的基因数量==城市数量
            # 注: 不包含最后回到的起点城市
            genes = [i for i in range(genes_len)]
            # 随机打乱顺序
            np.random.shuffle(genes)
        self.genes = genes
        self.genes_len = genes_len
        self.dist_mat = dist_mat
        self.fitness = self.cal_fitness()

    def cal_fitness(self):
        """
        计算适应度函数 --> 计算该个体按某种顺序遍历城市的距离之和
        应该是数值越小, 适应度越高
        :return:
        """
        fitness = 0.0
        for i in range(0, self.genes_len - 1):
            from_city = self.genes[i]
            to_city = self.genes[i + 1]
            # 找到矩阵中相应的距离并累加到fitness
            fitness += self.dist_mat[from_city, to_city]
        # 由题意知最后还要回到起点
        fitness += self.dist_mat[self.genes[-1], self.genes[0]]
        return fitness
